package com.xc.quickstart.common.util;

import org.springframework.data.geo.Point;

import java.math.BigDecimal;
import java.text.DecimalFormat;

public class DistanceUtils {
    /** 地球半径 **/
    private final static double Earth_Radius = 6378.137f;
    /** 180° **/
    private static final DecimalFormat df = new DecimalFormat("0.000000");
    /**
     * 根据一点的坐标与距离，以及方向，计算另外一点的位置
     * @param angle 角度，从正北顺时针方向开始计算
     * @param startLong 起始点经度
     * @param startLat 起始点纬度
     * @param distance 距离，单位m
     * @return
     */
    public static Point calculateLocationByDistanceAndLocationAndDirection(double angle, double startLong, double startLat, double distance){
        //将距离转换成经度的计算公式
        double δ = distance/Earth_Radius;
        // 转换为radian，否则结果会不正确
        angle = Math.toRadians(angle);
        startLong = Math.toRadians(startLong);
        startLat = Math.toRadians(startLat);
        double lat = Math.asin(Math.sin(startLat)*Math.cos(δ)+Math.cos(startLat)*Math.sin(δ)*Math.cos(angle));
        double lon = startLong + Math.atan2(Math.sin(angle)*Math.sin(δ)*Math.cos(startLat),Math.cos(δ)-Math.sin(startLat)*Math.sin(lat));
        // 转为正常的10进制经纬度
        lon = Math.toDegrees(lon);
        lat = Math.toDegrees(lat);
        lon = new BigDecimal(lon).setScale(6,BigDecimal.ROUND_UP).doubleValue();
        lat = new BigDecimal(lat).setScale(6,BigDecimal.ROUND_UP).doubleValue();
        Point point = new Point(lon,lat);
        return point;
    }


    public static double getDistance(double lon1, double lat1, double lon2, double lat2) {

        double radLat1 = rad(lat1);
        double radLat2 = rad(lat2);

        double a = radLat1 - radLat2;
        double b = rad(lon1) - rad(lon2);

        double c = 2 * Math.asin(Math.sqrt(
                Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));

        c = c * 6378.137;// 6378.137赤道半径

        return Math.round(c * 10000d) / 10000d;

    }


    private static double rad(double d) {
        return d * Math.PI / 180.0;
    }
}
